package com.easyclearance.service.impl;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.easyclearance.baseutil.MailUtil;
import com.easyclearance.countryRegUtil.MalaysiaMadcRegUtil;
import com.easyclearance.dao.MailInfoMapper;
import com.easyclearance.dao.MalaysiatravinfoMapper;
import com.easyclearance.dao.OrdertravpassportMapper;
import com.easyclearance.dao.PassportInfoMapper;
import com.easyclearance.dao.TravelitineraryMapper;
import com.easyclearance.entity.MailInfo;
import com.easyclearance.entity.Malaysiatravinfo;
import com.easyclearance.entity.Ordertravpassport;
import com.easyclearance.entity.PassportInfo;
import com.easyclearance.entity.Travelitinerary;
import com.easyclearance.service.TravInfoService;
import com.easyclearance.service.WxuserService;
import com.easyclearance.wxutils.WxloginUtil;

@Service("wxuserService")
public class WxuserServiceimpl implements WxuserService {
	
//	@Autowired
//	private WxuserInfoMapper wxuserInfoMapper;
	@Resource
	private MailUtil mailUtil;
	@Autowired
	private WxloginUtil wxloginUtil;
	@Autowired
	private MailInfoMapper mailInfoMapper;
	@Autowired
	private TravInfoService travInfoService;
//	@Autowired
//	private TravinfoCodeMapper travinfoCodeMapper;
	@Resource
	private MalaysiaMadcRegUtil malaysiaMadcRegUtil;
	@Autowired
	private OrdertravpassportMapper ordertravpassportMapper;
	@Autowired
	private PassportInfoMapper passportInfoMapper;
	@Autowired
	private MalaysiatravinfoMapper malaysiatravinfoMapper;
//	@Autowired
//	private SingaporeTravInfoMapper singaporeTravInfoMapper;
//	@Autowired
//	private TravelCodeRelationMapper travelCodeRelationMapper;
	@Autowired
	private TravelitineraryMapper travelitineraryMapper;
	
	public static final Logger logger = Logger.getLogger(WxuserServiceimpl.class);
	@Override
	public Map<String, Object> getWxopenid(Map<String, Object> paramMap) {
		// TODO Auto-generated method stub
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			if (Objects.nonNull(paramMap) && paramMap.containsKey("code")) {
				String code = paramMap.get("code").toString();
				//获取openid
				String openid = wxloginUtil.get(code);
				resultMap.put("openId", openid);
			}else {
				throw new Exception("code参数不能为空！");
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return resultMap;
	}
	@Override
	public Map<String, Object> addWxuserInfo(Map<String, Object> paramMap) {
		// TODO Auto-generated method stub
		//获取微信登陆信息
		paramMap.get("");
		return null;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void afterPaySubmit(String orderid) {
		// TODO Auto-generated method stub
        //////////////
        ////判断是否办理的是马来西亚电子签
        //////////////
		logger.info("进入发邮件请求");
        try {
			List<MailInfo> mailInfoList = mailInfoMapper.selectList(new QueryWrapper<MailInfo>().eq("email_status", 2));
	        // 打乱集合顺序
	        Collections.shuffle(mailInfoList);
	        MailInfo mailInfo = new MailInfo();
	        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(mailInfoList)) {
				mailInfo = mailInfoList.get(0);
			}
//        	String goCountryCode = orderInfo.getEcCountry();
    		List<Ordertravpassport> orderTravelPassportInfo = ordertravpassportMapper.selectList(new QueryWrapper<Ordertravpassport>().eq("orderid", orderid));
    		if (CollectionUtils.isNotEmpty(orderTravelPassportInfo)) {
				for (int i = 0; i < orderTravelPassportInfo.size(); i++) {
					Ordertravpassport ordertravpassport = orderTravelPassportInfo.get(i);
					//获取护照信息
        			String ecppid = ordertravpassport.getEcppid();
        			PassportInfo passportInfo = passportInfoMapper.selectOne(new QueryWrapper<PassportInfo>().eq("id", ecppid));
        			logger.error("护照信息："+JSON.toJSONString(passportInfo));
        			Map<String, Object> convertMalaysiaPassportSubmitInfo = travInfoService.convertPassportSubmitInfo(passportInfo,"0060");
        			
        			//获取旅行信息
        			String travid = ordertravpassport.getTravid();
			        Travelitinerary travelitinerary = travelitineraryMapper.selectById(travid);
			        logger.error("行程信息："+JSON.toJSONString(travelitinerary));
			        if (Objects.nonNull(travelitinerary)) {
						String[] titCodeArr = travelitinerary.getTitCode().split("-");
						for (int j = 0; j < titCodeArr.length; j++) {
							String titcode = titCodeArr[j];
							logger.error("国家码："+titcode);
                			if (Objects.equals(titcode, "0060")) {
								Malaysiatravinfo malaTravInfo = malaysiatravinfoMapper.selectOne(new QueryWrapper<Malaysiatravinfo>().eq("titid", travid).eq("trow", j+1));
								logger.error("旅行信息："+JSON.toJSONString(malaTravInfo));
								Map<String, Object> convertMalaysiaTravelSubmitInfo = travInfoService.convertMalaysiaTravelSubmitInfo(malaTravInfo);
								//创建容器
								Map userParams = new HashMap();
						        userParams.put("mdacVisaCountry","ALL");
						        userParams.put("hdCurrLang","ms");						        
						        userParams.put("email",mailInfo.getEmailLogin());
						        userParams.put("confirmEmail",mailInfo.getEmailLogin());
						        userParams.put("submitRegistration","Submit");
						        if (Objects.nonNull(convertMalaysiaTravelSubmitInfo) && Objects.nonNull(convertMalaysiaPassportSubmitInfo)) {
									userParams.putAll(convertMalaysiaTravelSubmitInfo);
									userParams.putAll(convertMalaysiaPassportSubmitInfo);
							        logger.error("----------------发起请求:"+JSON.toJSONString(userParams)+"------------------------");
									boolean register = malaysiaMadcRegUtil.register(userParams);
									logger.error("请求成功："+register);
								}
                			}
							/*else if (titcode.contains("0065")) {
								SingaporeTravInfo singporeTravInfo = singaporeTravInfoMapper.selectOne(new QueryWrapper<SingaporeTravInfo>().eq("titid", travid).eq("trow", j+1));
								logger.error("马来西亚:"+JSON.toJSONString(singporeTravInfo));
								//转换成对象json
								JSONObject parseObject = JSONObject.parseObject(JSON.toJSONString(passportInfo));
								Iterator<String> iterator = parseObject.keySet().iterator();
								String mailString = "<h3>订单id：</span><span class=\"NUE\">"+orderid+"</span></h3>"+"<h4>护照信息：</h4>";
								while(iterator.hasNext()) {
									String key2 = iterator.next();
									if (!key2.equals("id") && !key2.equals("pubts")) {
										String value = parseObject.getString(key2);
										mailString = mailString + "<p class=\"h\"><span class=\"k\">" + key2 + " :</span><span class=\"NUE\">"+value+"</span></p>";
									}
									mailString = mailString + "<h4>旅行信息：</h4>";
									JSONObject parseObject2 = JSONObject.parseObject(JSON.toJSONString(singporeTravInfo));
									Iterator<String> iterator2 = parseObject2.keySet().iterator();
									while (iterator2.hasNext()) {
										String key3 = iterator2.next();
										if (!key3.equals("id") && !key3.equals("pubts")) {
											String value = parseObject.getString(key3);
											mailString = mailString + "<p class=\"h\"><span class=\"k\">" + key3 + " :</span><span class=\"NUE\">"+value+"</span></p>";
										}
									}
								}
								logger.error("------发送新加坡邮件------");
								mailUtil.sendEmail(mailString, mailInfo);
                			}*/
						}
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

}
